import { Button, message, Modal, Popconfirm, Table } from 'antd';
import { memo, useEffect, useRef, useState } from 'react';
import type { QueryMoneyCardListParams } from '../services'
import { delMoneyCard, queryMoneyCardList } from '../services'
import { useRequest } from 'ahooks'
import dayjs from 'dayjs'

export interface CardListModalProps {
  onCancel?: () => void
  infoId?: number
}

const CardListModal: React.FC<CardListModalProps> = props => {
  const params = useRef<QueryMoneyCardListParams>({
    pageNum: 1, pageSize: 10
  })
  // 选中的行
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const { data, run, loading, refresh } = useRequest(queryMoneyCardList, {manual: true})
  const { runAsync: delMoneyCardAsync } = useRequest(delMoneyCard, {manual: true})
  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys:any) => {
      setSelectedRowKeys(selectedKeys);
    },
    getCheckboxProps: (record:any) => ({
      disabled: record.nickname, // 根据条件禁用某些行
    }),
  };
  const onCancel = () => {
    props.onCancel?.()
  }

  // 批量删除函数
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一条数据');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        // 过滤掉选中的行
        delMoneyCardAsync({
          ids: selectedRowKeys.join(','),
        })
          .then(() => {

            message.success('删除成功');
            refresh();
          })
      },
    });
  };

  useEffect(() => {
    if (props.infoId) {
      params.current.pageNum = 1
      params.current.infoId = props.infoId
      run(params.current)
    }
  }, [props.infoId])

  return (
    <Modal
      title='卡列表1'
      open={!!props.infoId}
      onCancel={onCancel}
      footer={false}
      width={1200}
    >
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          danger
          onClick={handleBatchDelete}
          disabled={selectedRowKeys.length === 0}
        >
          批量删除 ({selectedRowKeys.length})
        </Button>
      </div>
      <Table
        rowKey='id'
        loading={loading}
        dataSource={data?.data}
        rowSelection={rowSelection}
        scroll={{x: 'max-content'}}
        pagination={{
          pageSize: params.current.pageSize,
          total: data?.totalCount,
          onChange: (page, pageSize) => {
            params.current.pageNum = page === params.current.pageNum ? 1 : page
            params.current.pageSize = pageSize
            run(params.current)
          }
        }}
        columns={[
          {title: '卡标题', dataIndex: 'title', render: val => val || '--'},
          {title: '兑换码', dataIndex: 'cardCode'},
          {title: '已使用金额(元)', dataIndex: 'cutMoney'},
          {title: '卡面额(元)', dataIndex: 'fullMoney'},
          {title: '截止日期', dataIndex: 'endTime', render: val => val ? dayjs(val).format('YYYY-MM-DD') : '--'},
          {title: '兑换人昵称', dataIndex: 'nickname', render: val => val || '--'},
          {title: '兑换人手机号', dataIndex: 'telephone', render: val => val || '--'},
          {title: '操作', key: 'operation', width: 60, fixed: 'right', render: (_, record) => {
            return record.nickname ? null : <Popconfirm
              title={`确定删除现金卡: ${record.title} 吗?`}
              onConfirm={() => delMoneyCardAsync({id: record.id}).then(refresh)}
              okText="删除"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          }},
        ]}
      />
    </Modal>
  )
}

export default memo(CardListModal)